import { Button, Form, FormItem, Input, Message } from '@arco-design/web-vue'
import { useClipboard } from '@vueuse/core'
import IconCopy from '~icons/icons/copy'

import { deleteDnsAuthorityNodeApi, getDnsAuthorityInstallCommandApi } from '@/apis/modules/dns'

export default function useCommand(reload: () => void) {
  const handleCommand = (
    command: string,
    ids: string[],
    row?: any,
  ) => {
    const map: Record<string, () => void> = {
      delete: () => {
        const nameVerification = reactive({ name: '' })
        const disabled = computed(() => nameVerification.name !== row?.name)
        const loading = ref(false)
        const modalReturn = ref()

        const fn = () => {
          loading.value = true
          console.log('ids: ', ids)
          deleteDnsAuthorityNodeApi({ id: ids[0] as string })
            .then(() => {
              Message.success('操作成功')
              modalReturn.value.close()
              reload()
            })
            .finally(() => loading.value = false)
        }

        // 删除节点
        modalReturn.value = ModalHelper.error(
          {
            maskClosable: false,
            okText: '删除',
            width: 480,
            title: '删除节点',
            content: () => {
              return row?.ip
                ? (
                    <div class="w-full flex flex-col gap-y-6 text-#1D2129">
                      <span class={`text-[#1D2129] `}>
                        确定删除并卸载 “
                        {row?.name}
                        ” 节点吗？，此操作无法撤销。
                      </span>
                      <div class="w-full">
                        <Form layout="vertical" model={nameVerification}>
                          <FormItem
                            asteriskPosition="end"
                            field="name"
                            validateTrigger="blur"
                            hide-asterisk
                          >
                            {{
                              label: () => (
                                <span class="text-#1D2129">
                                  请输入「
                                  <span class="text-red-500">{row?.name}</span>
                                  」确认
                                </span>
                              ),
                              default: () => (
                                <Input
                                  class="mb-2px w-full"
                                  modelValue={nameVerification.name}
                                  maxLength={32}
                                  onInput={(v) => {
                                    nameVerification.name = v
                                  }}
                                  placeholder=""
                                >
                                </Input>
                              ),
                            }}
                          </FormItem>
                        </Form>
                      </div>
                    </div>
                  )
                : (
                    <div>
                      确定删除 “
                      <span class="text-red-500">{row?.name}</span>
                      ”  节点吗？
                    </div>
                  )
            },
            footer: () => {
              return row?.ip
                ? (
                    <div class="flex justify-end">
                      <Button onClick={() => modalReturn.value.close()} class="mr-4">
                        取消
                      </Button>
                      <Button
                        status="danger"
                        disabled={disabled.value}
                        class={disabled.value ? 'bg-[#FBACA3]!' : ''}
                        style={disabled.value ? '' : ''}
                        onClick={() => fn()}
                        loading={loading.value}
                      >
                        我已知晓后果并确认删除
                      </Button>
                    </div>
                  )
                : null
            },
          },
          fn,
        )
      },
      install_script: async () => {
        const { renderInstallScript, getScript, formState } = getInstallScript()
        await getScript(ids[0] as string)
        if (!formState.url)
          return false
        ModalHelper.confirm({
          title: '安装命令',
          maskClosable: false,
          footer: false,
          width: 480,
          content: renderInstallScript,
        })
      },
    }
    map[command]()
  }
  return { handleCommand }
}

/**
 *
 * 安装脚本弹窗
 */
function getInstallScript() {
  const formState = reactive({ url: '' })
  const { copy } = useClipboard({ legacy: true })
  const handleCopy = (content: string) => {
    copy(content)
    Message.success('复制成功')
  }
  async function getScript(id: string) {
    await getDnsAuthorityInstallCommandApi({
      id,
    })
      .then((res) => {
        formState.url = res.command ?? ''
      })
      .catch(() => {
        return true
      })
  }
  const renderInstallScript = () => (
    <div class="mb-[12px] w-full flex flex-col gap-y-6 text-[#1D2129]">
      <div class="flex justify-between gap-4 rounded-2 bg-#1D2129 p-4 text-white">
        <div>{formState.url}</div>
        <div>
          <div
            class="w-20px flex cursor-pointer items-center gap-x-6px text-white"
            onClick={() => handleCopy(formState.url ?? '')}
          >
            <IconCopy />
          </div>
        </div>
      </div>
    </div>
  )

  return {
    formState,
    getScript,
    renderInstallScript,
  }
}
